﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.Web.UI;

namespace PeppeDotNet.SP2010.TakeAPicture
{
    public class TakeAPictureFieldControl : BaseFieldControl
    {
        public TakeAPictureFieldControl()
        { }

        private HtmlInputHidden hiddenFilename;
        private HtmlGenericControl initParams;        

        protected override void CreateChildControls()
        {
            if (Field == null) return;
            base.CreateChildControls();
            if (ControlMode == SPControlMode.Display)
                return;

            try { Web.GetList(String.Format("{0}/Lists/TakeAPicture", Web.Url)); }
            catch
            {
                Controls.Clear();
                Controls.Add(new LiteralControl("You have to activate the feature!"));
                return;
            }

            hiddenFilename = (HtmlInputHidden)TemplateContainer.FindControl("hiddenFilename");
            if (hiddenFilename == null)
                throw new ArgumentException("InputHidden not found");

            initParams = (HtmlGenericControl)TemplateContainer.FindControl("initParams");
            if (initParams == null)
                throw new ArgumentException("InitParams not found");

            InsertParameters("");
        }

        protected override string DefaultTemplateName
        {
            get { return "TakeAPictureFieldControl"; }
        }

        public override object Value
        {
            get
            {
                EnsureChildControls();
                return hiddenFilename.Value.Trim();
            }
            set
            {
                EnsureChildControls();
                hiddenFilename.Value = (string)value;
                InsertParameters(value);
            }
        }

        private void InsertParameters(object value)
        {
            SPWeb web = SPContext.Current.Web;
            SPList images = web.GetList(String.Format("{0}/Lists/TakeAPicture", web.Url));
            initParams.Attributes["value"] = String.Format("Image={0},HiddenFieldID={1},ListID={2},MS.SP.url={3}/{4},WebUrl={5}", (string)value, hiddenFilename.ClientID, images.ID, SPContext.Current.Site.Url, web.ServerRelativeUrl, web.Url);
        }

        protected override void RenderFieldForDisplay(System.Web.UI.HtmlTextWriter output)
        {
            output.Write("<img src='{0}' />", ItemFieldValue);
        }
    }
}
